﻿namespace _4_NovaAdmin.Web.Core.Idempotency;

public class MemoryCacheIdempotencyStore : IIdempotencyStore, ISingletonDependency
{
    private readonly IMemoryCache _cache;
    private readonly TimeSpan _expiration;

    public MemoryCacheIdempotencyStore(IMemoryCache cache, IOptions<IdempotencyOptions> options)
    {
        _cache = cache;
        _expiration = TimeSpan.FromHours(options.Value.ExpirationHours);
    }

    public Task<bool> TryCreateRecordAsync(string key, string response)
        => Task.FromResult(_cache.TryGetValue(key, out _) ? false : _cache.Set(key, response, _expiration) != null);

    public Task<string?> GetResponseAsync(string key)
        => Task.FromResult(_cache.TryGetValue(key, out string? value) ? value : null);
}
